package com.jwpdk.dbframework;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import org.apache.log4j.Logger;
/**
 * 
 * @author 王志伟
 *
 */
public class SimpleStatement implements IStatement {

	private final Logger	log	= Logger.getLogger(this.getClass());
	private Statement		statement;
	private String			sqlstr;
	private SQL[]			sqlstrs;
	private Connection		conn;

	/**
	 * construct function
	 * @param conn
	 * @param sqlstr
	 * @throws Exception
	 */
	public SimpleStatement(Connection conn, SQL sql) throws Exception {
		this.conn = conn;
		statement = conn.createStatement();
		this.sqlstr = sql.getAskSql();
	}

	/**
	 * construct function
	 * @param conn
	 * @param sqlsstr
	 * @throws Exception
	 */
	public SimpleStatement(Connection conn, SQL[] sqls) throws Exception {
		this.conn = conn;
		statement = conn.createStatement();
		this.sqlstrs = sqls;

	}

	/**
	 * get sql
	 * @return String
	 * @throws Exception
	 */
	public String getSql() throws Exception {
		return sqlstr;
	}

	/**
	 * get statement
	 * @return Statement
	 * @throws Exception
	 */
	public Statement getStatement() throws Exception {
		return statement;
	}

	/**
	 * get Connection
	 * @return Statement
	 * @throws Exception
	 */
	public Connection getConnection() throws Exception {
		return conn;
	}

	/**
	 * execute query
	 * @return ResultSet
	 * @throws Exception
	 */
	public ResultSet executeQuery() throws Exception {
		try {
			long beginTime = System.currentTimeMillis();
			ResultSet result = statement.executeQuery(sqlstr);
			DAOBase.getExecuteTimeBySql(log,beginTime);
			return result;
		} catch ( java.sql.SQLException e ) {
			log.error("ERROR SQL： " + sqlstr);
			throw e;
		}
	}

	/**
	 * execute update
	 * @return int
	 * @throws Exception
	 */
	public int executeUpdate() throws Exception {
		try {
			long beginTime = System.currentTimeMillis();
			int result = statement.executeUpdate(sqlstr);
			DAOBase.getExecuteTimeBySql(log,beginTime);
			return result;
		} catch ( java.sql.SQLException e ) {
			log.error("ERROR SQL： " + sqlstr);
			throw e;
		}
	}

	/**
	 * execute batch
	 * @return int[]
	 * @throws Exception
	 */
	public int[] executeBatch() throws Exception {
		for (int i = 0; i < sqlstrs.length; i++) {
			statement.addBatch(sqlstrs[i].getAskSql());
		}
		long beginTime = System.currentTimeMillis();
		int[] result = statement.executeBatch();
		DAOBase.getExecuteTimeBySql(log,beginTime);
		return result;
	}

	/**
	 * close statement
	 * @throws Exception
	 */
	public void close() throws Exception {
		if ( statement != null )
			statement.close();
	}

}